﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Inmeta.TFS.MergeWorkItemsEventHandler
{
    public static class Extensions
    {
        public static Changeset GetChangeset(this TeamFoundationRequestContext requestContext, int changesetId)
        {
            var s = requestContext.GetService<TeamFoundationVersionControlService>();
            TeamFoundationDataReader reader = s.QueryChangeset(requestContext, changesetId, true, false, true);

            return reader.Current<Changeset>();
        }

        public static TfsTeamProjectCollection GetCollection(this TeamFoundationRequestContext requestContext)
        {
            var pc = requestContext.GetService<TeamFoundationLocationService>();
            var uri = pc.GetSelfReferenceUri(requestContext, pc.GetServerAccessMapping(requestContext));
            return new TfsTeamProjectCollection(uri);
        }

        public static TfsTeamProjectCollection GetImpersonatedCollection(this TeamFoundationRequestContext requestContext, string userToImpersonate)
        {
            var pc = requestContext.GetService<TeamFoundationLocationService>();
            var uri = pc.GetSelfReferenceUri(requestContext, pc.GetServerAccessMapping(requestContext));
            return ImpersonatedCollection.CreateImpersonatedCollection(uri, userToImpersonate);            
        }

        public static IEnumerable<Microsoft.TeamFoundation.VersionControl.Client.Change> PendingMerges(this Microsoft.TeamFoundation.VersionControl.Client.Change[] changes)
        {
            return changes.Where(ch => (ch.ChangeType & Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Merge) == Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Merge);
        }

        public static bool ContainsArtifact(this LinkCollection links, string artifactUri)
        {
            return links.OfType<ExternalLink>().Select(l => l).Any(el => el.LinkedArtifactUri == artifactUri);
        }
    }
}
